import rclpy
from rclpy.node import Node
from base_interfaces_demo.msg import SensorData
from pymongo import MongoClient
import datetime

class SensorDataSubscriber(Node):
    def __init__(self):
        super().__init__('sensor_data_subscriber')
        # 创建订阅者，订阅/sensor_data主题
        self.subscription = self.create_subscription(
            SensorData,
            '/sensor_data',
            self.sensor_callback,
            10)
        # 连接MongoDB
        self.client = MongoClient('192.168.85.121', 27017)
        self.db = self.client['sensor_db']
        self.collection = self.db['sensor_data']
        self.get_logger().info("MongoDB连接成功，开始监听传感器数据...")
        # 注册节点关闭时的回调
        # self.add_on_shutdown_callback(self.on_shutdown)

    def sensor_callback(self, msg):
        """处理接收到的传感器数据并存储到数据库"""
        try:
            # 构造数据文档
            data = {
                'temperature': msg.temperature,
                'humidity': msg.humidity,
                'timestamp': datetime.datetime.now()
            }
            # 插入数据库
            self.collection.insert_one(data)
            # 限流日志输出（每5秒最多一次）
            self.get_logger().info(
                f"数据已存储：温度{msg.temperature:.1f}°C, 湿度{msg.humidity:.1f}%",
                throttle_duration_sec=5
            )
        except Exception as e:
            self.get_logger().error(f"存储数据失败: {str(e)}")

    # def on_shutdown(self):
    #     """节点关闭时关闭数据库连接"""
    #     self.client.close()
    #     self.get_logger().info("MongoDB连接已关闭")

def main(args=None):
    rclpy.init(args=args)
    node = SensorDataSubscriber()
    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        pass
    finally:
        node.destroy_node()
        rclpy.shutdown()

if __name__ == '__main__':
    main()